import * as React from 'react';
import { Form, Field, DatePicker, Select, Badge } from '@teamix/ui';
import { YunxiaoIcon, ButtonIcon } from '@alife/devops-ui';
import MemberTrigger from 'components/memberTrigger';
import Popup from 'components/popup';
import dayjs from 'dayjs';
import intl from '../../../../../../../../locale';

const { RangePicker } = DatePicker;

const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    fixedSpan: 12,
  },
};

const statusMap = [
  {
    label: intl.get({
      id: 'code-assets.containers.advancedSearch.Success',
      defaultMessage: '成功',
    }),
    value: 'SUCCESS',
  },

  {
    label: intl.get({
      id: 'code-assets.containers.advancedSearch.Running',
      defaultMessage: '运行中',
    }),
    value: 'RUNNING',
  },

  {
    label: intl.get({ id: 'code-assets.containers.advancedSearch.Failed', defaultMessage: '失败' }),
    value: 'FAIL',
  },

  {
    label: intl.get({
      id: 'code-assets.containers.advancedSearch.Canceled',
      defaultMessage: '已取消',
    }),
    value: 'CANCELED',
  },

  {
    label: intl.get({
      id: 'code-assets.containers.advancedSearch.Waiting',
      defaultMessage: '等待中',
    }),
    value: 'WAITING',
  },
];

export default class FilterForm extends React.Component {
  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      authorData: [],
      hasDot: false,
    };
  }

  setFormInit = () => {
    this.field.setValues({
      status: '',
      start_time: null,
      end_time: null,
      extern_uids: [],
      range: null,
    });

    this.setState({
      authorData: [],
    });
  };

  onSearchResult = () => {
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        formData.extern_uids = formData.extern_uids || [];
        if (formData.status || formData.range || formData.extern_uids.length) {
          this.setState({
            hasDot: true,
          });
        } else {
          this.setState({
            hasDot: false,
          });
        }
        formData.extern_uids = formData.extern_uids.join(',');
        if (formData.range) {
          formData.start_time = dayjs(formData.range[0]).format('YYYY-MM-DD HH:mm:ss');
          formData.end_time = dayjs(formData.range[1]).format('YYYY-MM-DD HH:mm:ss');
          delete formData.range;
        }
        const { branch_name } = this.props;
        if (branch_name) {
          formData.branch_name = branch_name;
        }
        this.props.setAdvancedSearch(formData);
      }
    });
  };

  onResetClick = () => {
    this.setFormInit();
    this.onSearchResult();
  };

  onRangePickerOk = () => {
    this.onSearchResult();
  };

  onBranchChange = (value) => {
    this.field.setValue('branch_name', value);
    this.onSearchResult();
  };

  onStatusChange = (value) => {
    this.field.setValue('status', value);
    this.onSearchResult();
  };

  onAuthorChange = (value) => {
    this.setState({
      authorData: value,
    });

    this.field.setValue(
      'extern_uids',
      value.map((item) => item._userId),
    );

    this.onSearchResult();
  };

  render() {
    const { init } = this.field;

    return (
      <Popup
        size="large"
        trigger={
          <Badge dot={this.state.hasDot}>
            <ButtonIcon name="filter-line" />
          </Badge>
        }
        triggerType="click"
        footer={
          <Form.Item style={{ marginBottom: '0px' }}>
            <Form.Reset
              text
              type="primary"
              style={{ border: 0 }}
              onClick={this.onResetClick}
              toDefault
              className="advanced-search-form-btn"
            >
              <YunxiaoIcon type="delete-line" />
              {intl.get({
                id: 'code-assets.containers.advancedSearch.ClearAllFilterConditions',
                defaultMessage: '清除所有筛选条件',
              })}
            </Form.Reset>
          </Form.Item>
        }
      >
        <Form {...formItemLayout} labelTextAlign="left" field={this.field}>
          <Form.Item
            label={intl.get({
              id: 'code-assets.containers.advancedSearch.RunningStatus',
              defaultMessage: '运行状态',
            })}
            {...formItemLayout}
          >
            <Select
              {...init('status', { initValue: '' })}
              followTrigger
              onChange={this.onStatusChange}
            >
              {statusMap.map((item) => (
                <Select.Option value={item.value}>{item.label}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.containers.advancedSearch.Operator',
              defaultMessage: '运行人',
            })}
          >
            <MemberTrigger
              onChange={(value) => {
                this.onAuthorChange(value);
              }}
              value={this.state.authorData}
              multiple
            />
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.containers.advancedSearch.Runtime',
              defaultMessage: '运行时间',
            })}
            style={{ marginBottom: 0 }}
          >
            <RangePicker
              {...init('range')}
              followTrigger
              popupAlign="tr br"
              onOk={this.onRangePickerOk}
              format="YYYY-MM-DD"
            />
          </Form.Item>
        </Form>
      </Popup>
    );
  }
}
